<template>
  <section>
    <div class="wrapper">
      <v-file-input v-model="file" title="上传" multiple width="100%" style="display: none" ref="fileRef" />
      <!--            <v-btn text="提交" width="200px" @click="submit"/>-->
      <!--            <div class="disc">
                    <img src="./madoka.jpg" alt="" />
                  </div>-->
      <explorer :negatives="Root.negatives" :data="Root.data" :total="Root.total" @add="Root.openFileDialog" />
    </div>
  </section>
</template>
<script setup lang="ts">
import SHA1 from 'crypto-js/sha1'
import { enc } from 'crypto-js'
/*const rotate = ref(0);
const style = computed(() => {
  return {
    transform: `rotate(${rotate.value}deg)`,
  };
});
const render = () => {
  rotate.value += 0.2;
  if (rotate.value > 360) rotate.value = 0;
  requestAnimationFrame(render);
};
render();*/

import fileApi from "@/api/fileApi.ts";
import Explorer from "@/components/windows/components/Explorer/Explorer.vue";

const fileRef = useTemplateRef("fileRef");
const file = ref();
const onUpload = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files[0]) {
    file.value = target.files[0];
  }
};
watch(
  () => file.value,
  (v) => {
    submit(v);
  },
);
const fileToSHA1 = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      const binary = reader.result as ArrayBuffer
      const wordArray = enc.Latin1.parse(String.fromCharCode(...new Uint8Array(binary)))
      const hash = SHA1(wordArray).toString()
      resolve(hash)
    }
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}
const submit = async (files: File[]) => {
  for (const file of files) {
    const { name, size } = file;
    const hash = await fileToSHA1(file);
    console.log(SHA1(hash).toString())
    const res = await fileApi.upload({ filename: name, size, hash: SHA1(hash).toString() }, file);
    Root.data.push(res?.id)
  }
};
const Root = (() => {
  const openFileDialog = (e) => {
    const path = e ?? "/";
    fileRef.value?.click();
  };
  const s = reactive({
    data: [] as any[],
    negatives: [] as any[],
    total: 0,
    openFileDialog,
  });
  return s;
})();
</script>
<style scoped>
img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 50px;
}

.disc {
  position: relative;
  width: 300px;
  height: 300px;
  border-radius: 50%;
  overflow: hidden;
  transform-origin: 50% 50%;
}
</style>
